package com.greateffect.littlebud.lib.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Build;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.zcs.autolayout.config.AutoLayoutConfig;

import com.greateffect.littlebud.lib.imageloader.listener.ImageLoadListener;
import com.greateffect.littlebud.lib.imageloader.transformation.GlideCircleTransform;
import com.greateffect.littlebud.lib.utils.LogUtil;

/**
 * Created by ZengCS on 2019/5/28.
 * E-mail:zengcs@vip.qq.com
 * Add:成都市天府软件园E3
 */
public class GlideStaticUtils {
    private static final String TAG = "GlideStaticUtils";

    public static void displayImage(String url, int defaultImage, ImageView imageView) {
        loadNormal(imageView.getContext(), url, defaultImage, imageView);
    }

    public static void displayImage(Context context, String imageUrl, ImageView imageView, int defaultImage) {
        loadNormal(context, imageUrl, defaultImage, imageView);
    }

    public static void displayImage(Context context, String imageUrl, ImageView imageView,
                                    int loadImage, int errorImage, final ImageLoadListener listener) {
        LogUtil.w(TAG, "displayImage() called with: imageUrl = [" + imageUrl + "]");
        Glide.with(context).load(imageUrl)
                .placeholder(loadImage)
                .error(errorImage)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String s, Target<GlideDrawable> target, boolean b) {
                        if (listener != null) {
                            if (e != null) {
                                listener.loadImageFail(e.getMessage());
                            } else {
                                listener.loadImageFail("图片加载失败，" + s);
                            }
                        }
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable glideDrawable, String s,
                                                   Target<GlideDrawable> target, boolean b,
                                                   boolean b1) {
                        if (listener != null) {
                            listener.loadImageSuccess();
                        }
                        return false;
                    }
                }).into(imageView);
    }

    private static void loadNormal(final Context ctx, final String url, int placeholder, ImageView imageView) {
        LogUtil.w(TAG, "loadNormal() called with: url = [" + url + "]");
        Glide.with(ctx).load(url).dontAnimate().placeholder(placeholder).diskCacheStrategy(DiskCacheStrategy.SOURCE).listener(new RequestListener<String, GlideDrawable>() {
            @Override
            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                return false;
            }
        }).into(imageView);
    }

    public static void displayCircleImage(String url, int defaultImage, ImageView imageView) {
        LogUtil.w(TAG, "displayCircleImage() called with: url = [" + url + "]");
        Glide.with(imageView.getContext()).load(url).placeholder(defaultImage)
                .transform(new GlideCircleTransform(imageView.getContext()))
                .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
    }

    public static void displayCircleBorderImage(String url, int defaultImage, ImageView imageView, int borderWidth, int borderColor) {
        LogUtil.w(TAG, "displayCircleBorderImage() called with: url = [" + url + "]");
        Glide.with(imageView.getContext()).load(url).placeholder(defaultImage)
                .transform(new GlideCircleTransform(imageView.getContext(), borderWidth, borderColor))
                .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
    }

    public static void displayGifImage(String url, int defaultImage, ImageView imageView) {
        loadGif(imageView.getContext(), url, defaultImage, imageView);
    }

    /**
     * load image with Glide
     */
    private static void loadGif(final Context ctx, String url, int placeholder, ImageView imageView) {
        LogUtil.w(TAG, "loadGif() called with: url = [" + url + "]");
        Glide.with(ctx).load(url).asGif()
                .placeholder(placeholder).skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE).listener(new RequestListener<String, GifDrawable>() {
            @Override
            public boolean onException(Exception e, String model, Target<GifDrawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(GifDrawable resource, String model, Target<GifDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                return false;
            }
        }).into(imageView);
    }

    public static void loadPicAsBitmap(Context context, String url, SimpleTarget<Bitmap> listener) {
        Glide.with(context)
                .load(url)
                .asBitmap()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(listener);
    }

    /**
     * 检查bitmap的尺寸，过大时在部分机型中无法加载
     * @param resource
     * @return
     */
    public static Bitmap checkBitmapSize(Bitmap resource){
        if(resource != null){
            //长宽有一个超过屏幕相应尺寸的2.5倍时，进行缩放
            //setImageBitmap bitmap的尺寸过大时在部分机型（如：T3）会无法加载，所以需要进行缩放
            float maxRatio = 2.5f;
            if("HUAWEI".equalsIgnoreCase(Build.BRAND) || "samsung".equalsIgnoreCase(Build.BRAND)){
                maxRatio = 2.5f;
            }else {
                maxRatio = 2.0f;
            }
            float maxWidth = AutoLayoutConfig.getInstance().getScreenWidth() * maxRatio;
            float maxHeight = AutoLayoutConfig.getInstance().getScreenHeight() * maxRatio;
            //有一个尺寸超过最大尺寸，则进行缩放
            if(resource.getHeight() >= maxHeight || resource.getWidth() >= maxWidth){
                float scale = Math.min(maxWidth / resource.getWidth(),maxHeight / resource.getHeight());
                Matrix matrix = new Matrix();
                matrix.setScale(scale, scale);
                resource = Bitmap.createBitmap( resource, 0, 0,  resource.getWidth(), resource.getHeight(), matrix, false);
            }
        }
        return resource;
    }
}
